#![allow(non_snake_case)]
use crate::TableState;
use leptos::{html::Ul, prelude::*};
use leptos_use::on_click_outside;
use shq_common::prelude::ContextMenus;
#[component]
pub(super) fn ContextMenusView(
    context_menus: StoredValue<ContextMenus>,
    table_state: ReadSignal<TableState>,
) -> impl IntoView {
    let context_action_index = table_state.with_untracked(|state| state.context_action_index);
    let curr_context_menu = table_state.with_untracked(|state| state.curr_context_menu);
    let menu_ref = NodeRef::<Ul>::new();
    let _ = on_click_outside(menu_ref, move |_| curr_context_menu.set(None));
    view! {
        <Show when=move || curr_context_menu.with(|ms|ms.is_some())>
            <ul node_ref=menu_ref class="fixed menu bg-base-200 rounded-box w-52" style=move||{
                let (x, y, col_name, data_type) = curr_context_menu.with(|ms|{
                    let ms=ms.as_ref().unwrap();
                    (ms.0,ms.1,ms.2.clone(),ms.3)
                });
                let count=context_menus.with_value(|cms| cms.get_context_menu_count(&col_name, data_type));
                calculate_position(x, y, count as i32)
            }>
            {move || {
                let (cname, data_type) = curr_context_menu.with(|ms|{
                    let ms=ms.as_ref().unwrap();
                    (ms.2.clone(),ms.3)
                });
                let context_menu_list = context_menus.with_value(|cms| cms.get_cell_context_menu_list(&cname, data_type));
                context_menu_list.into_iter().map(|menu| {
                    view! {
                        <li><a on:click=move |ev| {
                            ev.prevent_default();
                            ev.stop_propagation();
                            context_action_index.set(Some(menu.0));
                            curr_context_menu.set(None);
                        }>{menu.1}</a></li>
                    }
                }).collect::<Vec<_>>()
            }}
        </ul>
        </Show>
    }
}

fn calculate_position(x: i32, y: i32, count: i32) -> String {
    let window = window();
    let menu_width = 208; // 菜单宽度（与CSS中定义一致）
    let menu_height = count * 36; // 估算的菜单高度
                                  // 获取窗口视口尺寸
    let viewport_width = window.inner_width().unwrap().as_f64().unwrap() as i32;
    let viewport_height = window.inner_height().unwrap().as_f64().unwrap() as i32;
    let adjusted_x = if x + menu_width > viewport_width {
        viewport_width - menu_width - 10 // 向右溢出时，向左调整
    } else {
        x
    };
    // 计算调整后的Y坐标（防止底部溢出）
    let adjusted_y = if y + menu_height > viewport_height {
        viewport_height - menu_height - 10 // 向下溢出时，向上调整
    } else {
        y
    };
    format!("left: {}px;top: {}px;", adjusted_x, adjusted_y)
}
